package com.vids.controller;

import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.fastjson2.JSON;
import com.vids.constant.GlobalConstant;
import com.vids.constant.Urlconstant;
import com.vids.constant.VIIDRespEnum;
import com.vids.hikcam.HIKCamAlarm;
import com.vids.model.entity.Ape;
import com.vids.model.entity.Register;
import com.vids.model.entity.SystemTime;
import com.vids.model.param.KeepaliveParam;
import com.vids.model.param.RegisterParam;
import com.vids.model.param.SystemTimeParam;
import com.vids.model.param.UnRegisterParam;
import com.vids.model.response.ResponseStatus;
import com.vids.service.IApeService;
import com.vids.service.IRegisterService;
import com.vids.utils.AlarmUtils;
import com.vids.utils.BeanUtilss;
import com.vids.utils.RestTemplateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("VIID")
public class RegisterController
{
    @Resource
    IRegisterService iRegistryService;

	@Value ("${dev_mode}")
	private boolean dev_mode = true;

	@Resource
	IApeService apeService;

	private static boolean isInited = false;

	@Resource
	AlarmUtils alarmUtils;

	static {
		HIKCamAlarm.sdk_net_dvr_init();
	}

	HashMap<String, Integer> ApesAlarmMap = new HashMap<String, Integer>();

	HashMap<String, Ape> ApesObjectMap = new HashMap<String, Ape>();

    @PostMapping(value = "System/Register", produces = "application/VIID+JSON")
    public Object register(@RequestBody RegisterParam param, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String deviceId = param.getRegisterObject().getDeviceID();
//	log.info("Enter into register====》 接受注册信息 deviceId-> {}", deviceId);

		ResponseStatus status = new ResponseStatus(Urlconstant.URL_REGISTER, VIIDRespEnum.OK.getCode(), new Date());
		 if (param == null || param.getRegisterObject() == null) {
            log.info("注册失败 -> {}", param.getRegisterObject().getDeviceID());
			status.setStatusCode(1);
			status.setStatusString("参数为空");
			return new ResponseEntity<>(BeanUtilss.objectToMap(BeanUtilss.getResponseModel(status)),
                    HttpStatus.OK);
		}
		Register vo = param.getRegisterObject();
		ResponseStatus responseStatus = iRegistryService.register(vo);

		String statusString = responseStatus.getStatusString();

		if (CharSequenceUtil.isNotBlank(statusString)
			&& (statusString.indexOf("成功") != -1 || statusString.indexOf("已经注册") != -1)) {

			response.setHeader(GlobalConstant.USER_IDENTIFY, vo.getDeviceID());
		}else {
			//如果当前网络摄像头是海康威视，则需要设置人脸和车辆图片抓取告警
			if (!dev_mode) {

				//生成一个apeId和ip_addr的映射文件，在后续的保存图片文件中使用。
//				if (!isInited) {
//					alarmUtils.getApeMapJson();
////					log.info(JSON.toJSONString(alarmUtils.getApeMapJson()));
//					ApesObjectMap = alarmUtils.getApeObjectMap();
//					log.info(JSON.toJSONString(ApesObjectMap));
//					isInited = true;
//				}

//

			}
		}

		Map<String, Object> map = BeanUtilss.objectToMap(BeanUtilss.getResponseModel(responseStatus));

//		log.info("register====》 response json: "+JSON.toJSON(map));
		return new ResponseEntity(map, HttpStatus.OK);
    }

	public boolean isHikCamera(Ape ape)
	{
		return ape.getModel().contains("DS-2CD7");
	}

    @PostMapping(value = "System/UnRegister", produces = "application/VIID+JSON")
    public Object unRegister(@RequestBody UnRegisterParam param, HttpServletResponse response) throws Exception
	{
		ResponseStatus status = new ResponseStatus(Urlconstant.URL_UNREGISTER, VIIDRespEnum.OK.getCode(), new Date());
		if (param == null || param.getUnRegisterObject() == null) {
			status.setStatusCode(1);
			status.setStatusString("参数为空");
			return new ResponseEntity<Map<String, Object>>(BeanUtilss.objectToMap(BeanUtilss.getResponseModel(status)),
				HttpStatus.CREATED);
		}

		Register vo = param.getUnRegisterObject();

//		log.info("unRegiste 接受注销信息 deviceId-> {}", vo.getDeviceID());

		ResponseStatus responseStatus = iRegistryService.unRegister(vo);
		String statusString = responseStatus.getStatusString();
		if (CharSequenceUtil.isNotBlank(statusString) && statusString.indexOf("成功") != -1) {
			response.setHeader(GlobalConstant.USER_IDENTIFY, vo.getDeviceID());
		}

//		if (!dev_mode) {
//			String deviceId = param.getUnRegisterObject().getDeviceID();
//			Ape ape = ApesObjectMap.get(deviceId);
//			if ((null != ape) && isHikCamera(ape) && ApesAlarmMap.containsKey(deviceId)) {
//				log.info("unRegiste deviceId ====================>" + deviceId);
//				//登录用户注销
//				HIKCamAlarm.stopApeAlarm(ApesAlarmMap.get(deviceId));
////				HIKCamAlarm.sdk_net_dvr_cleanup();
//				ApesAlarmMap.remove(deviceId);
//			}
//		}

		return new ResponseEntity<Map<String, Object>>(
			BeanUtilss.objectToMap(BeanUtilss.getResponseModel(responseStatus)), HttpStatus.OK);
    }

    @PostMapping(value = "System/Keepalive", produces = "application/VIID+JSON")
    public Object keepLive(@RequestBody KeepaliveParam param, HttpServletRequest request) throws Exception {
//		log.info("Enter into keepLive====================>");
		log.info("keepLive 信息 -> {}", param.getKeepaliveObject().getDeviceID());

		ResponseStatus status = new ResponseStatus(Urlconstant.URL_KEEPALIVE, VIIDRespEnum.OK.getCode(), new Date());
		if ( param.getKeepaliveObject() == null) {
			status.setStatusCode(1);
			status.setStatusString("参数为空");
			return new ResponseEntity<>(BeanUtilss.objectToMap(BeanUtilss.getResponseModel(status)),
                    HttpStatus.OK);
		}
		Register vo = param.getKeepaliveObject();
		ResponseStatus responseStatus = iRegistryService.keepLive(vo);
//		log.info("register====》 response json: "+JSON.toJSON(responseStatus));

		return new ResponseEntity<>(
                BeanUtilss.objectToMap(BeanUtilss.getResponseModel(responseStatus)), HttpStatus.OK);
    }

    @GetMapping(value = "System/Time", produces = "application/VIID+JSON")
    public Object getSystemTime() throws Exception {
		log.info("Enter into getSystemTime====================>");
		SystemTime time = iRegistryService.time();
		if (time == null) {
			return new ResponseEntity<Map<String, Object>>(new HashMap<String, Object>(), HttpStatus.NO_CONTENT);
		}
		SystemTimeParam param = new SystemTimeParam();
		param.setSystemTimeObject(time);

		log.info("Exit getSystemTime====================>");
		return param;
    }

}
